
//
//  RMFlipViewController.m
//  rmplanner
//
//  Created by Andrew Pigram on 18/05/12.
//  Copyright (c) 2012 PiAMP Productions. All rights reserved.
//

#import "RMFlipViewController.h"
#import "RMAllergyViewController.h"

@interface RMFlipViewController ()

@property (nonatomic) BOOL notify;

@end

@implementation RMFlipViewController

@synthesize notify, cell, retData;
static BOOL vote = NO;

#pragma mark UITableViewController functions

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    if ([[[NSUserDefaults standardUserDefaults] valueForKey:@"Notify"] boolValue])
	{
		cell.accessoryType = UITableViewCellAccessoryCheckmark;
	}
	else
	{
		cell.accessoryType = UITableViewCellAccessoryNone;
	}
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
		return (interfaceOrientation == UIInterfaceOrientationPortrait);
	else
		return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}

#pragma mark UITableView delegate functions
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	if (indexPath.section == 1)
	{
		switch (indexPath.row)
		{
			case 0:
				if (cell.accessoryType != UITableViewCellAccessoryCheckmark)
				{
					cell.accessoryType = UITableViewCellAccessoryCheckmark;
					notify = YES;
				}
				else
				{
					cell.accessoryType = UITableViewCellAccessoryNone;
					notify = NO;
				}
				[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
				break;
			case 2:
				[self logout];
				break;
		}
	}
	else if (indexPath.section == 2)
	{
		if (indexPath.row == 0)
		{
			// cancel vote
			UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Cancel Vote" message:@"Are you sure you wish to cancel your current vote?" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil];
			[alertView show];
			vote = YES;
		}
		else
		{
			// cancel order
			UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Cancel Order" message:@"Are you sure you wish to cancel your current order?" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil];
			[alertView show];
			vote = NO;
		}
		[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
	}
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
	if (buttonIndex == 1 && [alertView.title isEqualToString:@"Cancel Vote"])
	{
		NSURL* url = [[NSURL alloc] initWithScheme:@"http" host:@"rmplanner.net" path:@"/kitchen/scripts/cancelVote"];
		NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
		NSData* data = [[NSString stringWithFormat:@"user_id=%d", [[NSUserDefaults standardUserDefaults] integerForKey:@"uid"]] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
		[request setHTTPBody:data];
		[request setHTTPMethod:@"POST"];
		NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
		[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
		NSAssert((connection != nil), @"Failed to create a connection");
	}
	else if (buttonIndex == 1 && [alertView.title isEqualToString:@"Cancel Order"])
	{
		NSURL* url = [[NSURL alloc] initWithScheme:@"http" host:@"rmplanner.net" path:@"/kitchen/scripts/cancelOrder"];
		NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
		NSData* data = [[NSString stringWithFormat:@"user_id=%@", [[NSUserDefaults standardUserDefaults] valueForKey:@"uid"]] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
		[request setHTTPBody:data];
		[request setHTTPMethod:@"POST"];
		NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
		[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
		NSAssert((connection != nil), @"Failed to create a connection");
	}
}

#pragma mark Interface Builder selectors
// save user settings and dismiss view
- (IBAction)save
{
	// save the user settings to the user defaults singleton
	[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:notify] forKey:@"Notify"];
    if (notify)
        // register for all 3 types of push notifications
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge];
    else
        // deregister push notifications
        [[UIApplication sharedApplication] unregisterForRemoteNotifications];
    
    // dismiss the view
	[self.navigationController popViewControllerAnimated:YES];
}

// cancel changes and return to previous view
- (IBAction)cancel
{
	// dismiss the view without any changes
	[self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)logout
{
	[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"credentials"];
	[[NSUserDefaults standardUserDefaults] setValue:@"" forKey:@"user"];
	[[NSUserDefaults standardUserDefaults] setValue:@"" forKey:@"password"];
	[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"Notify"];
	[[UIApplication sharedApplication] unregisterForRemoteNotifications];
	
	NSData* data = [[NSString stringWithFormat:@"devtoken=%@", [[NSUserDefaults standardUserDefaults] valueForKey:@"devToken"]] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
	NSURL* url = [[NSURL alloc] initWithScheme:@"http" host:@"rmplanner.net" path:@"/kitchen/scripts/logout"];
	NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
	[request setHTTPBody:data];
	[request setHTTPMethod:@"POST"];
	NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:nil startImmediately:YES];
	NSAssert((connection != nil), @"Failed to create a connection");
	[[NSUserDefaults standardUserDefaults] setValue:@"" forKey:@"devToken"];
	[self dismissModalViewControllerAnimated:YES];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	retData = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	[retData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	connection = nil;
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	NSString* response = [[NSString alloc] initWithData:retData encoding:NSUTF8StringEncoding];
	NSLog(@"%@", response);
	if ([response isEqualToString:@"good"])
	{
		if (vote)
		{
			UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Your vote was cancelled successfully" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
			[alertView show];
		}
		else
		{
			UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Your order was cancelled successfully" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
			[alertView show];
		}
	}
	else if ([response isEqualToString:@"fail"])
	{
		UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Failure" message:@"Your request could not be completed. Please try again." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alertView show];
	}
	else
	{
		UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Past cut-off" message:@"Your request could not be completed as the cut-off time has now passed." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alertView show];
	}
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	connection = nil;
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	
	UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Could not connect to server. Your request has not been processed. Please try again." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[alertView show];
}

@end
